package com.iraeta.service.sys.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.ImmutableMap;
import com.iraeta.Config;
import com.iraeta.common.OkHttpClientRest;
import com.iraeta.common.URL;
import com.iraeta.dao.main.DJFileDao;
import com.iraeta.entity.main.DJFile;
import com.iraeta.entity.main.DJFileProcessStatus;
import com.iraeta.service.sys.FileService;
import com.iraeta.uitl.FileUtils;
import com.iraeta.uitl.Util;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;

@Service
public class FileServiceImpl implements FileService {
    private static final Logger logger = LoggerFactory.getLogger(FileServiceImpl.class);

    @Autowired
    Config config;
    @Autowired
    DJFileDao djFileDao;
    @Autowired
    FileProcessFrist fileProcessFrist;

    @Override
    public void downloadFile(String token, String path, String fileName) throws Exception {
        String downloadPathResponse = OkHttpClientRest.doPostForToken(URL.DOWN_FILE_URL, token, JSON.toJSONString(ImmutableMap.of("path", path)));
        String downloadUrl = JSONObject.parseObject(downloadPathResponse).getString("downloadUrl");
        FileUtils.downloadFile(downloadUrl, config.OUTPUT_FILE_PATH + "/" +fileName);
    }

    @Override
    public void checkDjNewFile() throws Exception {
        String loginResponse = OkHttpClientRest.doPost(URL.LOGIN_URL, JSON.toJSONString(ImmutableMap.of("name", config.DJ_NAME, "password", config.DJ_PASSWORD)));
        String token = JSONObject.parseObject(loginResponse).getString("token");
        String pathResponse = OkHttpClientRest.doPost(URL.LIST_FILES_INFO_URL,
                JSON.toJSONString(ImmutableMap.of("token", token, "path", "group:25769803776" + config.GROUP_FILE_PATH)));
        JSONArray files = JSONObject.parseObject(pathResponse).getJSONArray("items");
        files.forEach(
                e -> {
                    JSONObject o = ((JSONObject) e);
                    JSONObject fileInfo = o.getJSONObject("fileInfo");
                    String fileName = fileInfo.getString("name");
                    try {
                        DJFile djFile = djFileDao.selectByFileName(fileName);
                        boolean isNewFile = false;
                        if (djFile == null) {
                            isNewFile = true;
                        } else if (fileInfo.getLong("c_mtime") > djFile.getDjFileTime()) {   //如果鼎甲文件新  //!fileInfo.getLong("c_mtime").equals(djFile.getDjFileTime())
                            isNewFile = true;
                        }
                        boolean isExcelFile = true;
                        if(o.getBoolean("hasChildren")){
                            isExcelFile = false;
                        }else if(!fileInfo.getString("suffix").equals("xlsx")){
                            isExcelFile = false;
                        }
                        if (isNewFile && isExcelFile) {
                            String fileNameWithoutSuffix = fileName.substring(0, fileName.lastIndexOf("."));
                            String downloadPath = fileNameWithoutSuffix + "_" + Util.getBusinessNo() + "." + fileInfo.getString("suffix");
                            djFileDao.insert(DJFile.builder()
                                    .fileName(fileName)
                                    .djFileTime(fileInfo.getLong("c_mtime"))
                                    .path(o.getString("protocol") + "/" + o.getString("path"))
                                    .downloadPath(downloadPath)
                                    .createTime(LocalDateTime.now().format(DateTimeFormatter.ofPattern("YYYY-MM-dd hh:mm:ss")))
                                    .statusId(DJFileProcessStatus.unProcess)
                                    .message("")
                                    .build());
                            downloadFile(token, o.getString("protocol") + "/" + o.getString("path"), downloadPath);
                        }
                    } catch (Exception ex) {
                        logger.error("[FileServiceImpl-checkDjNewFile]" + ex.getMessage());
                    }
                }
        );
    }

    @Override
    public void processDjFile() {
        List<DJFile> djFileList = djFileDao.selectByStatusId(DJFileProcessStatus.unProcess);
        for (DJFile djFile : djFileList) {
            if(djFile.getPath().contains("BIFileDownloadTest") && djFile.getFileName().contains("点检")){
                fileProcessFrist.processDjFile(djFile);
            }
            if(djFile.getPath().contains("BIFileDownloadTest") && djFile.getFileName().contains("设备档案")){
                fileProcessFrist.processDjFile(djFile);
            }
        }
    }
}
